﻿using System;
using System.Collections.Generic;
using System.IO;

namespace KstopaCommon
{
    public static class TxtFileHelper
    {
        public static bool ReadTxtFile(string filename, out List<string> content, ref string msg)
        {
            content = new List<string>();
            try
            {
                if (File.Exists(filename))
                {
                    FileStream fs = new FileStream(filename, FileMode.Open);
                    StreamReader sr = new StreamReader(fs);
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        content.Add(line);
                    }
                    sr.Close();
                    fs.Close();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception exc)
            {
                msg = exc.Message;
                return false;
            }
        }

        public static bool WriteTxtFile(string filename, List<string> content, ref string msg)
        {
            try
            {
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }
                FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                for (int i = 0; i < content.Count; i++)
                {
                    sw.WriteLine(content[i]);
                }
                sw.Close();
                fs.Close();
                return true;
            }
            catch (Exception exc)
            {
                msg = exc.Message;
                return false;
            }
        }

    }
}
